# -*- coding: utf-8 -*-

from __future__ import unicode_literals

from django.shortcuts import render
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.views.decorators.http import require_http_methods
from django.core import serializers
from django.views.decorators.csrf import csrf_exempt
from django.core.files.storage import default_storage
import time
import traceback
import sys
reload(sys)
sys.setdefaultencoding("utf-8")

#-------------project bag---------------------
from base import multithreading
from base import timer
from base.log import logger
from base import log
from base.emails import send_email
from base import excelworker
from base import config
from base.entity import goods_mgr
from base.entity import shoppingcar_mgr
from base.entity import user_mgr


#------------system start run--------------------
timer.set_timer()
USER_ID = str(config.getConfig('login','userID'))
user_mgr.register(USER_ID)
excelworker.open_excel()
goods_mgr.get_all_goodsID()
shoppingcar_mgr.get_all_cartID()
user_mgr.get_all_userName()



# timer.joinTimer_DateTimePoint(test1,2017,11,22,16,01,15,('test',))

logger.info('你的登陆ID是:'+str(USER_ID))

def test(request):
    try:
        return HttpResponse('测试成功')
    except:
        logger.info(traceback.print_exc())
        return HttpResponse('测试不通过')


def register(request):
    send_email(message="系统test!!!")
    logger.info("view the register part.")
    return render(request, "register.html")


def register_handle(request):
    context = {}
    if request.POST:
        context['username'] = request.POST['username']
    return render(request, "register_status.html", context)


@require_http_methods(["GET"])
def get_items(request):
    response = {}
    response['items'] = [{"name": "miho"}, {"name": "hoyi"}]
    response['msg'] = 'success'
    response['error_num'] = 0
    return JsonResponse(response)


@csrf_exempt
def get_carTypes(request):
    response = {}
    try:
        response['data'] = excelworker.get_sheet_data('carTypes')
        response['code'] = 0
        response['msg'] = 'success' 
    except:
        response['data'] = []
        response['code'] = 1
        response['msg'] = 'failed'
        logger.error('cannot get carTypes')
    return JsonResponse(response)

@csrf_exempt
def get_repairPosition(request):
    response = {}
    try:
        response['data'] = excelworker.get_sheet_data('repairPos')
        response['code'] = 0
        response['msg'] = 'success' 
    except:
        response['data'] = []
        response['code'] = 1
        response['msg'] = 'failed'
        logger.error('cannot get repairPosition')
    return JsonResponse(response)

@csrf_exempt
def get_partsTypes(request):
    response = {}
    try:
        response['data'] = excelworker.get_sheet_data('partsTypes')
        response['code'] = 0
        response['msg'] = 'success' 
    except:
        response['data'] = []
        response['code'] = 1
        response['msg'] = 'failed'
        logger.error('cannot get partsTypes')
    return JsonResponse(response)


@csrf_exempt
def get_all_goods(request):
    response = {}
    try:
        response['data'] = goods_mgr.c_get_all_goodsDetail()
        response['code'] = 0
        response['msg'] = 'success'
    except:
        response['data'] = []
        response['code'] = 1
        response['msg'] = 'failed'
        logger.error('cannot get all goods')
    return JsonResponse(response)

def get_my_shoppingCart(request):
    response = {}
    name = request.POST.get('userID')
    # if not name:
    #     name = USER_ID 
    name = USER_ID 
    print name
    print user_mgr.UserObj(name).c_get_myCart()
    try:
        response['data'] = user_mgr.UserObj(name).c_get_myCart()
        response['code'] = 0
        response['msg'] = 'success'
    except:
        response['data'] = []
        response['code'] = 1
        response['msg'] = 'failed'
        logger.error('cannot get all %s cart' % (name))
    return JsonResponse(response)

@csrf_exempt
def add_shoppingCart(request):
    response = {}
    try:
        userID = USER_ID
        goodsID = request.POST.get('goodsID')
        goodsNum = 1
        goodsPrice = goods_mgr.GoodsObj(goodsID).get_goodsPrice()
        shoppingcar_mgr.add_cart(userID,goodsID,goodsNum,goodsPrice)
        shoppingcar_mgr.get_all_cartID()
        response['code'] = 0
        response['msg'] = 'success'
    except:
        response['code'] = 1
        response['msg'] = 'failed'
    return JsonResponse(response)
    

@csrf_exempt
def del_shoppingCart(request):
    print request.POST.get('userName')
    response = {}
    try:
        userName = request.POST.get('userName')
        cartID = request.POST.get('cartID')
        shoppingCartObj = shoppingcar_mgr.ShoppingCartObj(int(cartID))
        if not userName == shoppingCartObj.get_userID():
            response['code'] = 2
            response['msg'] = 'failed'
            return JsonResponse(response)
        shoppingCartObj.del_Cart()
        response['code'] = 0
        response['msg'] = 'success'
    except:
        response['code'] = 1
        response['msg'] = 'failed'
    return JsonResponse(response)


@csrf_exempt
def clear_shoppingCart(request):
    response = {}
    # userName = request.POST.get('userName')
    # if not userName:
    userName = USER_ID
    try:
        cart_list = user_mgr.UserObj(userName).get_myCart()
        for cart in cart_list:
            cart.del_Cart()
        response['code'] = 0
        response['msg'] = 'success'
    except:
        response['code'] = 1
        response['msg'] = 'failed'
    print response
    return JsonResponse(response)

@csrf_exempt
def goods_soldOut(request):
    response = {}
    a = goods_mgr.GoodsObj(1)
    a.del_goods()
    return HttpResponse('测试成功')

@csrf_exempt
def get_goods_msg(request):
    print request.FILES
    print request.POST
    response = {}
    response['msg'] = 'success'
    return JsonResponse(response)   